package com.huadao.cart_ccs.main.login;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import com.daolion.base.anotation.BsActivityAnnotation;
import com.daolion.base.utils.ActivityUtil;
import com.google.gson.JsonElement;
import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseActivity;
import com.huadao.cart_ccs.common.ExperimentStageManager;
import com.huadao.cart_ccs.common.GsonUtil;
import com.huadao.cart_ccs.common.ParamsPreferences;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.QRCodeUtil;
import com.huadao.cart_ccs.common.dialog.DialogFragmentHelper;
import com.huadao.cart_ccs.common.dialog.IDialogResultListener;
import com.huadao.cart_ccs.data.bean.DeviceInfo;
import com.huadao.cart_ccs.data.source.http.RetrofitHelper;
import com.huadao.cart_ccs.experiment.home.ExperimentActivity;
import com.huadao.cart_ccs.experiment.preprocessing.PreProcessingActivity;
import com.huadao.cart_ccs.greendao.entity.Project;
import com.huadao.cart_ccs.main.CartApplication;
import com.huadao.cart_ccs.main.CommandService;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


@BsActivityAnnotation(layoutId = R.layout.activity_login)
public class LoginActivity extends BaseActivity implements LoginContract.ILoginView {

    @BindView(R.id.iv_QR) ImageView iv_QR;
    private LoginPresenter presenter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = new LoginPresenter(this);
        Intent intent = new Intent(this, CommandService.class);
        startService(intent);
        //1. 第一步，创建项目
        presenter.createDevice();
    }


    @OnClick(R.id.iv_QR)
    public void onClickQRCode() {
        presenter.login();
    }


    private void generateQRcode(DeviceInfo deviceInfo) {
        JsonElement jsonElement = GsonUtil.getInstance().getGson().toJsonTree(deviceInfo);
        jsonElement.getAsJsonObject().addProperty("loginCode", presenter.getLoginCode());
        String jsonStr = jsonElement.toString();
//        String info=GsonUtil.getInstance().getGson().toJson(deviceInfo);
        Bitmap bitmap = QRCodeUtil.createQRCodeBitmap(jsonStr, 200, 200);
        iv_QR.setImageBitmap(bitmap);
    }

    @Override
    protected void onDestroy() {
        presenter.detachView();
        super.onDestroy();
    }

    @Override
    public void createDeviceResult(DeviceInfo deviceInfo) {
        if (deviceInfo == null) {
            DialogFragmentHelper.showConfirmDialog(this, "", "重试创建设备?", new IDialogResultListener<Integer>() {
                @Override
                public void onDataResult(Integer result) {
                    if (result == DialogInterface.BUTTON_POSITIVE) {
                        presenter.createDevice();
                    }
                }
            }, false);
        } else {
            CartApplication.getInstance().setDeviceInfo(deviceInfo);
            ParamsPreferences.getInstance().setDeviceInfoCommit(deviceInfo);
            //因为有了设备信息，需要传设备ID，所有重新初始化RetrofitHelper，并且要new LoginPresenter，否则LoginPresenter的api还是使用之前的Retrofit
            RetrofitHelper.getInstance(this).reInit();
            presenter.reInit();
            generateQRcode(deviceInfo);
            //2. 第二步 循环读取该设备的项目
            queryProjectWithDelay(2, deviceInfo.getId());
        }
    }

    @Override
    public void onQueryProjectResult(com.huadao.cart_ccs.data.bean.Project project) {
        if (project != null && project.isBinded()) {//绑定成功
            CartApplication.getInstance().setSystemProject(project);
            presenter.checkLastProject();
            showToast("登陆成功");
        } else {
//            showToast("设备未登陆");
            queryProjectWithDelay(1, CartApplication.getInstance().getDeviceInfo().getId());
        }
    }

    private void queryProjectWithDelay(int delay, final String devId) {
        Observable.timer(delay, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        presenter.queryProject(devId);
                    }
                });
    }

    @Override
    public void onLoginResult() {
        presenter.checkLastProject();
    }

    @Override
    public void onCheckLastProject(final Project project) {
        if (project != null && project.getEndTime() == null) {
//            resumeLastProject();
//            showLoading("正在恢复项目...");
            DialogFragmentHelper.showTwoOperateDialog(this, "发现未完成的项目", "是否恢复项目？" + "(ID:" + project.getProjectId() + ")", R.string.positive_resume_project, R.string.negative_resume_project, new IDialogResultListener<Integer>() {
                @Override
                public void onDataResult(Integer result) {
                    if (result == DialogInterface.BUTTON_POSITIVE) {
                        resumeLastProject();
                        showLoading("正在恢复项目...");
                    } else if (result == DialogInterface.BUTTON_NEGATIVE) {
                        startNewProject();
                        showLoading("正在新建项目...");
                    }
                }
            }, false);
        } else {
            startNewProject();
        }
    }

    private void resumeLastProject() {
        Observable.create(new ObservableOnSubscribe<Map<String,Integer>>() {
            @Override
            public void subscribe(ObservableEmitter<Map<String,Integer>> emitter) throws Exception {
                int res_pro = ProjectManager.getInstance().resumeProject();
                int res_exp = ExperimentStageManager.getInstance().resumeStage();
                Map<String,Integer> resultMap = new HashMap<>();
                resultMap.put("project", res_pro);
                resultMap.put("exp", res_exp);
                emitter.onNext(resultMap);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Map<String,Integer>>() {
                    @Override
                    public void accept(Map<String,Integer> map) throws Exception {
                        int res_pro = map.get("project");
                        int res_exp = map.get("exp");
                        String info_pro = res_pro == ProjectManager.STATUE_SUCC ? "恢复项目成功" : "恢复项目失败";
                        String info_exp = res_exp == ExperimentStageManager.STATUE_SUCC ? "恢复实验阶段成功" : "恢复实验阶段失败";
                        Log.i(TAG, info_pro + " " + info_exp);
                        showToast(info_pro + " " + info_exp);
                        if (res_pro == ProjectManager.STATUE_SUCC && res_exp == ExperimentStageManager.STATUE_SUCC) {
                            if (ExperimentStageManager.getInstance().getCurrentStage().getDay() == 0) {//上次实验准备阶段还没完成
                                Intent intent = new Intent(LoginActivity.this, PreProcessingActivity.class);
//                                Intent intent = new Intent(LoginActivity.this, ExperimentActivity.class);
                                intent.putExtra("isNewPorject", false);
                                startActivity(intent);
                            } else {//上次实验已经进入培养阶段
                                Intent intent = new Intent(LoginActivity.this, ExperimentActivity.class);
                                intent.putExtra("isNewPorject", false);
                                startActivity(intent);
                            }
                            LoginActivity.this.finish();
                        } else {
                            hideLoading();
                            DialogFragmentHelper.showMessageDialog(LoginActivity.this, "恢复失败", info_pro + "," + info_exp);
                        }
                    }
                });
    }

    private void startNewProject() {
        Observable.create(emitter -> {
            ProjectManager.getInstance().initProject();
            ExperimentStageManager.getInstance().initStage();
            emitter.onNext(new Object());
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    Intent intent = new Intent(LoginActivity.this, PreProcessingActivity.class);
                    startActivity(intent);
                    LoginActivity.this.finish();
                });
    }
}
